package test.http.core.it;

import blue.base.core.common.ErrorCode;
import blue.http.core.annotation.Filter;
import blue.http.core.filter.HttpFilter;
import blue.http.core.message.HttpRequest;
import blue.http.core.message.HttpResponse;
import io.netty.handler.codec.http.HttpResponseStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Jin Zheng
 * @since 1.0 2021-08-24
 */
@Filter(filters = "/**", excludes = {"/user/reg", "/user/login"})
public class TokenFilter implements HttpFilter {
	private static Logger logger = LoggerFactory.getLogger(TokenFilter.class);

	private UserService userService = UserService.INSTANCE;

	public TokenFilter() {
	}

	@Override
	public boolean preHandle(HttpRequest request, HttpResponse response) throws Exception {
		String token = request.getHeader("X-Token");
		User user = userService.getByToken(token);
		if (user == null) {
			response.setHttpStatus(HttpResponseStatus.UNAUTHORIZED);
			response.setResult(ErrorCode.INVALID_TOKEN.toJsonString());
			return false;
		}

		return true;
	}
}
